package com.TheyChat.service.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.TheyChat.service.config.auth.UserContext;
import com.TheyChat.service.config.core.enums.StatusEnum;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: victor.w.ye
 * @Date: 2021/2/23 10:19
 * @Copyright:
 * @Company: luban
 * @Version: 1.0.0
 **/
@Component
public class EntityMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "status", StatusEnum.class, StatusEnum.VALID);
        if (UserContext.getCurrentUser() != null) {
            this.strictInsertFill(metaObject, "createUser", String.class, UserContext.getCurrentUser().getUserRealName());
            this.strictInsertFill(metaObject, "editUser", String.class, UserContext.getCurrentUser().getUserRealName());
        } else {
            this.strictInsertFill(metaObject, "createUser", String.class, "system");
            this.strictInsertFill(metaObject, "editUser", String.class, "system");
        }

        LocalDateTime now = LocalDateTime.now();
        metaObject.setValue("createTime", null);
        metaObject.setValue("editTime", null);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "editTime", LocalDateTime.class, now);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("editUser", null);
        metaObject.setValue("editTime", null);
        this.strictUpdateFill(metaObject, "editTime", LocalDateTime.class, LocalDateTime.now());
        if (UserContext.getCurrentUser() != null) {
            this.strictUpdateFill(metaObject, "editUser", String.class, UserContext.getCurrentUser().getUserRealName());

        } else {
            this.strictUpdateFill(metaObject, "editUser", String.class, "system");
        }
    }
}
